package cz.muni.fi.pa165.travelagency.web.frontend;

import com.samaxes.stripes.ejb3.EJBBean;
import cz.muni.fi.pa165.travelagency.api.entities.ITour;
import cz.muni.fi.pa165.travelagency.api.services.ICustomerService;
import cz.muni.fi.pa165.travelagency.api.services.IOrderService;
import cz.muni.fi.pa165.travelagency.api.services.IPackageTourService;
import cz.muni.fi.pa165.travelagency.dto.CustomerDTO;
import cz.muni.fi.pa165.travelagency.dto.OrderDTO;
import cz.muni.fi.pa165.travelagency.dto.PackageTourDTO;
import cz.muni.fi.pa165.travelagency.dto.TourDTO;
import java.math.BigDecimal;
import java.util.Date;
import javax.ejb.EJB;
import javax.ejb.EJBs;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.RedirectResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


@UrlBinding("/order/{$event}/{package-tour.id}")
@EJBs({
    @EJB(name = "orderService", beanInterface = IOrderService.class),
    @EJB(name = "ptourService", beanInterface = IPackageTourService.class),
    @EJB(name = "customerService", beanInterface = ICustomerService.class)
})
public class OrderActionBean implements ActionBean{

    final static Logger log = LoggerFactory.getLogger(OrderActionBean.class);
    private ActionBeanContext context;
    
    @ValidateNestedProperties(value = {
        @Validate(on = {"submit"}, field = "numberOfPersons", required = true, minvalue=1, expression="this <= packageTourAvailablePlaces")
    })
    private OrderDTO order;
    
    private PackageTourDTO packageTour;
    
    @ValidateNestedProperties(value = {
            @Validate(on = {"submit"}, field = "name", required = true, maxlength=100),
            @Validate(on = {"submit"}, field = "address", required = true),
            @Validate(on = {"submit"}, field = "phoneNumber", required = true, maxlength=16, mask="^(\\+)?([ \\d]){5,14}([\\d]).$")            
    })        
    private CustomerDTO customer;
    
    @EJBBean("java:comp/env/orderService")
    private IOrderService orderService;
    
    @EJBBean("java:comp/env/ptourService")
    private IPackageTourService ptService;
    
    @EJBBean("java:comp/env/customerService")
    private ICustomerService customerService;    

    @Override
    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    @Override
    public ActionBeanContext getContext() {
        return context;
    }

    public void setOrder(OrderDTO order){
        this.order = order;
    }
    
    public OrderDTO getOrder() {
        return order;
    }

    public PackageTourDTO getPackageTour() {
        return packageTour;
    }
    
    public int getPackageTourAvailablePlaces() {
        return ptService.getAvailablePlaces(packageTour);
    }    

    public CustomerDTO getCustomer() {
        return customer;
    }

    public void setCustomer(CustomerDTO customer) {
        this.customer = customer;
    }
    
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"create", "submit"})
    public void loadPackageTourFromDatabase() {
        String id = context.getRequest().getParameter("package-tour.id");
        if (id == null) {
            return;
        }
        
        packageTour = (PackageTourDTO) ptService.getPackageTour(Long.parseLong(id));
    }
    
    @Before(stages = LifecycleStage.BindingAndValidation, on = {"order-created"})
    public void loadOrderFromDatabase() {
        log.debug("params={}", context.getRequest().getParameterMap());
        String id = context.getRequest().getParameter("order.id");
        if (id == null) {
            return;
        }
        
        order = (OrderDTO) orderService.getOrder(Long.parseLong(id));
    }    
    
    @DefaultHandler
    public Resolution create() {
        return new ForwardResolution("/frontend/order_create.jsp");
    }
    
    public Resolution submit() {
        customerService.createCustomer(customer);
        
        order.setCustomer(customer);
        order.setOrderedPackageTour(packageTour);
        order.setCreated(new Date());
        order.setPaid(false);
        
        BigDecimal price = packageTour.getPricePerPerson();
        
        for (ITour t: packageTour.getAvailableTours()) {
            String ordered = context.getRequest().getParameter(t.getId().toString());
            if (Boolean.parseBoolean(ordered)) {
                order.getOrderedTours().add((TourDTO)t);
                price = price.add(t.getPricePerPerson());
            }
        }
        
        price = price.multiply(new BigDecimal(order.getNumberOfPersons()));
        order.setPrice(price);
        
        orderService.createOrder(order);
        Resolution res = new RedirectResolution(this.getClass(), "order-created").addParameter("order.id", order.getId());
        return res;
    }
    
    public Resolution cancel() {
        return new RedirectResolution(PackageTourActionBean.class);
    }    
    
    @HandlesEvent(value="order-created")
    public Resolution orderCreated() {
        return new ForwardResolution("/frontend/order_result.jsp");
    }
}
